<script setup lang="ts">
import { ref, onMounted, computed } from "vue";

import { useScrollBarDragger } from "@renderer/utils/dragger";

const currentValue = defineModel();
const currentLabel = computed(() => {
  for (let i = 0; i < props.options.length; i++) {
    const opt = props.options[i];
    if (opt.value === currentValue.value) {
      return opt.label;
    }
  }
  return currentValue.value;
});

const props = withDefaults(
  defineProps<{
    title?: string;
    fullscreen?: boolean;
    placeholder?: string;
    steps?: Array<string>;
    options: Array<Option>;
  }>(),
  {
    title: "请选择",
    fullscreen: true,
    placeholder: "点击选择"
  }
);

const visible = ref(false);

// 设定选择框高度，为最大高度
const selectBoxHeight = ref(0);
onMounted(() => {
  const precent = props.fullscreen ? 1 : 0.75;
  selectBoxHeight.value = window.innerHeight * precent - 70 - 60 - 73;
  addEventListener(
    "resize",
    () => (selectBoxHeight.value = window.innerHeight * precent - 70 - 60 - 73)
  );
});

function toSelect() {
  visible.value = true;
}

// 用户完成选择后
function selected(_value: string | number) {
  currentValue.value = _value;
  visible.value = false;
}
// 设置滚动条
const selectScrollRef = ref(null);
const selectDragger = useScrollBarDragger(selectScrollRef);
</script>

<template>
  <div style="width: 100%">
    <el-input :value="currentLabel" :placeholder="props.placeholder" readonly @click="toSelect" />
    <el-dialog v-model="visible" :fullscreen="props.fullscreen" :title="props.title">
      <el-scrollbar
        ref="selectScrollRef"
        class="select-box"
        :height="selectBoxHeight - 57 + 'px'"
        @mousedown="selectDragger.mouseDownHandler"
        @mouseup="selectDragger.mouseUpHandler"
        @mousemove="selectDragger.mouseMoveHandler"
        @mouseleave="selectDragger.mouseUpHandler"
      >
        <el-space class="select-space" direction="vertical">
          <el-button
            v-for="item in props.options"
            :key="item.value"
            class="select-btn"
            size="large"
            :type="item.value === currentValue ? 'primary' : ''"
            plain
            @click="selected(item.value)"
            >{{ item.label }}</el-button
          >
        </el-space>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss">
.select-box {
  margin: 24px 0 0 0;
  .select-space {
    width: 100%;
  }
}
.select-btn {
  width: 100% !important;
  height: 56px !important;
}
:deep(.el-space__item) {
  width: 100%;
}
</style>
